package com.chujiekeji.test.activity;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chujiekeji.test.R;
import com.chujiekeji.test.account.AccountHelper;
import com.chujiekeji.test.activity.chat.AppCache;
import com.chujiekeji.test.activity.chat.ChatActivity;
import com.chujiekeji.test.activity.chat.model.Callback;
import com.chujiekeji.test.api.ChujieApi;
import com.chujiekeji.test.base.BaseActivity;
import com.chujiekeji.test.BaseApplication;
import com.chujiekeji.test.base.BaseConstant;
import com.chujiekeji.test.base.BaseActivity;
import com.chujiekeji.test.base.BaseToast;
import com.chujiekeji.test.bean.ResultBean;
import com.chujiekeji.test.bean.User;
import com.chujiekeji.test.util.AppOperator;
import com.chujiekeji.test.util.DialogHelper;
import com.chujiekeji.test.util.TDevice;
import com.chujiekeji.test.util.TLog;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.TextHttpResponseHandler;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

/**
 * @author MapleStory
 * @ qq 1002285057
 * @ project https://gitee.com/MapStory/Shopwt-Android
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener, View.OnFocusChangeListener{
    protected InputMethodManager mInputMethodManager;
    protected Toast mToast;
    private boolean mKeyBoardIsActive=false;
    private ProgressDialog mDialog;

    private LinearLayoutCompat llUsername;
    private LinearLayoutCompat llPassword;
    private Toolbar mainToolbar;
    private AppCompatEditText usernameEditText;
    private AppCompatEditText passwordEditText;
    private ImageView uernameDel;
    private ImageView passwordDel;

    private AppCompatTextView registerTextView;
    private AppCompatTextView findPassTextView;
    private AppCompatTextView loginTextView;
    private AppCompatImageView qqImageView;
    private AppCompatImageView wxImageView;
    private AppCompatImageView wbImageView;

    private long exitTimeLong;

    @Override
    public void initView() {

        setContentView(R.layout.activity_base_login);
        ButterKnife.bind(this);
        mainToolbar = findViewById(R.id.mainToolbar);
        usernameEditText = findViewById(R.id.usernameEditText);
        passwordEditText = findViewById(R.id.passwordEditText);
        registerTextView = findViewById(R.id.registerTextView);
        findPassTextView = findViewById(R.id.findPassTextView);
        loginTextView = findViewById(R.id.loginTextView);
        qqImageView = findViewById(R.id.qqImageView);
        wxImageView = findViewById(R.id.wxImageView);
        wbImageView = findViewById(R.id.wbImageView);
        llUsername = findViewById(R.id.ll_username);
        llPassword = findViewById(R.id.ll_password);
        uernameDel = findViewById(R.id.iv_login_username_del);
        passwordDel = findViewById(R.id.iv_login_pwd_del);

    }
    public static void show(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void initData() {

        exitTimeLong = 0L;
        setToolbar(mainToolbar, "登录");

    }

    @Override
    public void initEven() {

        registerTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseApplication.get().start(getActivity(), RegisterActivity.class);
            }
        });

        findPassTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BaseApplication.get().start(getActivity(), FindPassActivity.class) ;
            }
        });

        loginTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginRequest();
            }
        });

        qqImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        wxImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        wbImageView.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {

           }
        });

        usernameEditText.setOnFocusChangeListener(this);
        usernameEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @SuppressWarnings("deprecation")
            @Override
            public void afterTextChanged(Editable s) {
                String username = s.toString().trim();
                if (username.length() > 0) {
                    uernameDel.setVisibility(View.VISIBLE);
                } else {
                    uernameDel.setVisibility(View.INVISIBLE);
                }

//                String pwd = mEtLoginPwd.getText().toString().trim();
//                if (!TextUtils.isEmpty(pwd)) {
//                    mBtLoginSubmit.setBackgroundResource(R.drawable.bg_login_submit);
//                    mBtLoginSubmit.setTextColor(getResources().getColor(R.color.white));
//                } else {
//                    mBtLoginSubmit.setBackgroundResource(R.drawable.bg_login_submit_lock);
//                    mBtLoginSubmit.setTextColor(getResources().getColor(R.color.account_lock_font_color));
//                }

            }
        });

        passwordEditText.setOnFocusChangeListener(this);
        passwordEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @SuppressWarnings("deprecation")
            @Override
            public void afterTextChanged(Editable s) {
                int length = s.length();
                if (length > 0) {
                    passwordDel.setVisibility(View.VISIBLE);
                } else {
                    passwordDel.setVisibility(View.INVISIBLE);
                }

//                String username = mEtLoginUsername.getText().toString().trim();
//                if (TextUtils.isEmpty(username)) {
//                    showToastForKeyBord(R.string.message_username_null);
//                }
//                String pwd = mEtLoginPwd.getText().toString().trim();
//                if (!TextUtils.isEmpty(pwd)) {
//                    mBtLoginSubmit.setBackgroundResource(R.drawable.bg_login_submit);
//                    mBtLoginSubmit.setTextColor(getResources().getColor(R.color.white));
//                } else {
//                    mBtLoginSubmit.setBackgroundResource(R.drawable.bg_login_submit_lock);
//                    mBtLoginSubmit.setTextColor(getResources().getColor(R.color.account_lock_font_color));
//                }
            }
        });

    }

    @Override
    public void onReturn() {

            super.onReturn();

    }

    @Override
    public void onActivityResult(int req, int res, Intent data) {
        super.onActivityResult(req, res, data);
        if (res == Activity.RESULT_OK) {
            switch (req) {
                case BaseConstant.CODE_LOGIN:
                    BaseToast.get().show("登录成功！");
                    break;
                default:
                    break;
            }
        }
    }

    @SuppressWarnings("ConstantConditions")
    private void loginRequest() {

        String tempUsername = usernameEditText.getText().toString().trim();
        String tempPwd = passwordEditText.getText().toString().trim();


        if (!TextUtils.isEmpty(tempPwd) && !TextUtils.isEmpty(tempUsername)) {
            //登录成功,请求数据进入用户个人中心页面

            if (TDevice.hasInternet()) {
                requestLogin(tempUsername, tempPwd);
            } else {
                showToastForKeyBord(R.string.footer_type_net_error);
            }

        } else {
            showToastForKeyBord(R.string.login_input_username_hint_error);
        }

    }

    private void requestLogin(String tempUsername, String tempPwd) {
        ChujieApi.login(tempUsername, tempPwd, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                showFocusWaitDialog();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                requestFailureHint(throwable);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                TLog.i("login------","responseString:"+responseString);
                try {
                    Type type = new TypeToken<ResultBean<User>>() {
                    }.getType();

                    ResultBean<User> resultBean = AppOperator.createGson().fromJson(responseString, type);
                    if (resultBean.isSuccess()) {
                        final User user = resultBean.getResult();
                        user.setToken(resultBean.getToken());
                        user.chatServerOk = true;
//                        AppCache.getService().login(user.getHelpNum(), user.getNickName(), new Callback<Void>() {
//                            @Override
//                            public void onEvent(Context context, int code, String msg, Void aVoid) {
//                                if (code == 200) {
//                                    user.chatServerOk = true;
//                                }
//                            }
//                        });
                        if (user.chatServerOk){
                            if (AccountHelper.login(user, headers)) {
                                BaseApplication.showToast(R.string.login_success_hint);
                                finish();
                            } else {
                                showToastForKeyBord("登录异常");
                            }
                        }else {
                            showToastForKeyBord("聊天服务连接异常");
                        }
                    } else {
                        int code = resultBean.getCode();
                        String message = resultBean.getMessage();
                        if (code == 211) {
                            passwordEditText.setFocusableInTouchMode(false);
                            passwordEditText.clearFocus();
                            usernameEditText.requestFocus();
                            usernameEditText.setFocusableInTouchMode(true);
                            llUsername.setBackgroundResource(R.drawable.bg_login_input_error);
                        } else if (code == 212) {
                            usernameEditText.setFocusableInTouchMode(false);
                            usernameEditText.clearFocus();
                            passwordEditText.requestFocus();
                            passwordEditText.setFocusableInTouchMode(true);
                            message += "," + getResources().getString(R.string.message_pwd_error);
                            llPassword.setBackgroundResource(R.drawable.bg_login_input_error);
                        }
                        showToastForKeyBord(message);
                        //更新失败应该是不进行任何的本地操作
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    onFailure(statusCode, headers, responseString, e);
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                hideWaitDialog();
            }

            @Override
            public void onCancel() {
                super.onCancel();
                hideWaitDialog();
            }
        });
    }
    /**
     * hide waitDialog
     */
    protected void hideWaitDialog() {
        ProgressDialog dialog = mDialog;
        if (dialog != null) {
            mDialog = null;
            try {
                dialog.cancel();
                // dialog.dismiss();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    protected void showToastForKeyBord(@StringRes int id) {
        showToast(id);
    }

    protected void showToastForKeyBord(String message) {
        showToast(message);
    }

    protected void hideKeyBoard(IBinder windowToken) {
        InputMethodManager inputMethodManager = this.mInputMethodManager;
        if (inputMethodManager == null) return;
        boolean active = inputMethodManager.isActive();
        if (active) {
            inputMethodManager.hideSoftInputFromWindow(windowToken, 0);
        }
    }

    /**
     * request network error
     *
     * @param throwable throwable
     */
    protected void requestFailureHint(Throwable throwable) {
        if (throwable != null) {
            throwable.printStackTrace();
        }
        showToastForKeyBord(R.string.request_error_hint);
    }
    /**
     * sha-1 to hex
     *
     * @param tempPwd tempPwd
     * @return sha-1 pwd
     */
    @NonNull
    protected String getSha1(String tempPwd) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
            messageDigest.update(tempPwd.getBytes("utf-8"));
            byte[] bytes = messageDigest.digest();

            StringBuilder tempHex = new StringBuilder();
            // 字节数组转换为 十六进制数
            for (byte aByte : bytes) {
                String shaHex = Integer.toHexString(aByte & 0xff);
                if (shaHex.length() < 2) {
                    tempHex.append(0);
                }
                tempHex.append(shaHex);
            }
            return tempHex.toString();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return tempPwd;
    }

    /**
     * show FocusWaitDialog
     *
     * @return progressDialog
     */
    protected ProgressDialog showFocusWaitDialog() {

        String message = getResources().getString(R.string.progress_submit);
        if (mDialog == null) {
            mDialog = DialogHelper.getProgressDialog(this, message, false);//DialogHelp.getWaitDialog(this, message);
        }
        mDialog.show();

        return mDialog;
    }

    @SuppressLint("InflateParams")
    private void showToast(String text) {
        Toast toast = this.mToast;
        if (toast == null) {
            toast = initToast();
        }
        View rootView = LayoutInflater.from(this).inflate(R.layout.view_toast, null, false);
        TextView textView = (TextView) rootView.findViewById(R.id.title_tv);
        textView.setText(text);
        toast.setView(rootView);
        initToastGravity(toast);
        toast.show();
    }

    /**
     * showToast
     *
     * @param id id
     */
    @SuppressLint("InflateParams")
    private void showToast(@StringRes int id) {
        Toast toast = this.mToast;
        if (toast == null) {
            toast = initToast();
        }
        View rootView = LayoutInflater.from(this).inflate(R.layout.view_toast, null, false);
        TextView textView = (TextView) rootView.findViewById(R.id.title_tv);
        textView.setText(id);
        toast.setView(rootView);
        initToastGravity(toast);
        toast.show();
    }

    @NonNull
    private Toast initToast() {
        Toast toast;
        toast = new Toast(this);
        toast.setDuration(Toast.LENGTH_SHORT);
        this.mToast = toast;
        return toast;
    }

    private void initToastGravity(Toast toast) {
        toast.setGravity(Gravity.BOTTOM, 0, getResources().getDimensionPixelSize(R.dimen.toast_y_offset));
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int id = v.getId();

        if (id == R.id.usernameEditText) {
            if (hasFocus) {
                usernameEditText.setActivated(true);
                passwordEditText.setActivated(false);
            }
        } else {
            if (hasFocus) {
                usernameEditText.setActivated(true);
                passwordEditText.setActivated(false);
            }
        }
    }

    @OnClick({R.id.iv_login_username_del, R.id.iv_login_pwd_del})
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.iv_login_username_del:
                usernameEditText.setText(null);
                break;
            case R.id.iv_login_pwd_del:
                passwordEditText.setText(null);
                break;
            default:
                break;
        }

    }
}
